package com.nbsaas.boot;

import java.util.HashMap;
import java.util.Map;

public class KeywordFilterTrieWithCount {
    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("关键字1");
        trie.insert("关键字2");

        String text = "这是一段包含非法关键字的文本，关键字1和关键字2应该被过滤掉。";
        FilterResult result = filterKeywords(text, trie);
        
        System.out.println("过滤后的文本: " + result.filteredText);
        System.out.println("匹配到的非法关键字数量: " + result.keywordCount);
    }

    public static FilterResult filterKeywords(String text, Trie trie) {
        StringBuilder filteredText = new StringBuilder();
        int index = 0;
        int keywordCount = 0;

        while (index < text.length()) {
            TrieNode current = trie.root;
            int startIndex = index;

            while (index < text.length() && current.children.containsKey(text.charAt(index))) {
                current = current.children.get(text.charAt(index));
                index++;
            }

            if (current.isEndOfWord()) {
                // 当前位置匹配到关键字，替换为*
                filteredText.append("*".repeat(index - startIndex));
                keywordCount++;
            } else {
                filteredText.append(text.charAt(startIndex));
                index++;
            }
        }

        return new FilterResult(filteredText.toString(), keywordCount);
    }

    static class TrieNode {
        Map<Character, TrieNode> children;
        boolean endOfWord;

        public TrieNode() {
            this.children = new HashMap<>();
            this.endOfWord = false;
        }

        public boolean isEndOfWord() {
            return endOfWord;
        }

        public void setEndOfWord() {
            this.endOfWord = true;
        }
    }

    static class Trie {
        TrieNode root;

        public Trie() {
            this.root = new TrieNode();
        }

        public void insert(String word) {
            TrieNode current = root;
            for (char ch : word.toCharArray()) {
                current.children.putIfAbsent(ch, new TrieNode());
                current = current.children.get(ch);
            }
            current.setEndOfWord();
        }
    }

    static class FilterResult {
        String filteredText;
        int keywordCount;

        public FilterResult(String filteredText, int keywordCount) {
            this.filteredText = filteredText;
            this.keywordCount = keywordCount;
        }
    }
}
